from Utils.util import *

class RD_Maze:
    """
    递归分割算法生成迷宫
    """
    def __init__(self, rows, columns) -> None:
        self.num_rows = rows
        self.num_cols = columns

    def run(self) -> list:

        def Recursive_division(r1, r2, c1, c2, M, image):
            if r1 < r2 and c1 < c2:
                rm = random.randint(r1, r2-1)
                cm = random.randint(c1, c2-1)
                cd1 = random.randint(c1,cm)
                cd2 = random.randint(cm+1,c2)
                rd1 = random.randint(r1,rm)
                rd2 = random.randint(rm+1,r2)
                d = random.randint(1,4)
                if d == 1:
                    M[rd2, cm, 2] = 1
                    M[rd2, cm+1, 0] = 1
                    M[rm, cd1, 3] = 1
                    M[rm+1, cd1, 1] = 1
                    M[rm, cd2, 3] = 1
                    M[rm+1, cd2, 1] = 1
                elif d == 2:
                    M[rd1, cm, 2] = 1
                    M[rd1, cm+1, 0] = 1
                    M[rm, cd1, 3] = 1
                    M[rm+1, cd1, 1] = 1
                    M[rm, cd2, 3] = 1
                    M[rm+1, cd2, 1] = 1
                elif d == 3:
                    M[rd1, cm, 2] = 1
                    M[rd1, cm+1, 0] = 1
                    M[rd2, cm, 2] = 1
                    M[rd2, cm+1, 0] = 1
                    M[rm, cd2, 3] = 1
                    M[rm+1, cd2, 1] = 1
                elif d == 4:
                    M[rd1, cm, 2] = 1
                    M[rd1, cm+1, 0] = 1
                    M[rd2, cm, 2] = 1
                    M[rd2, cm+1, 0] = 1
                    M[rm, cd1, 3] = 1
                    M[rm+1, cd1, 1] = 1
        
                Recursive_division(r1, rm, c1, cm, M, image)
                Recursive_division(r1, rm, cm+1, c2, M, image)
                Recursive_division(rm+1, r2, cm+1, c2, M, image)
                Recursive_division(rm+1, r2, c1, cm, M, image)
        
            elif r1 < r2:
                rm = random.randint(r1, r2-1)
                M[rm,c1,3] = 1
                M[rm+1,c1,1] = 1
                Recursive_division(r1, rm, c1, c1, M, image)
                Recursive_division(rm+1, r2, c1, c1, M, image)
            elif c1 < c2:
                cm = random.randint(c1,c2-1)
                M[r1,cm,2] = 1
                M[r1,cm+1,0] = 1
                Recursive_division(r1, r1, c1, cm, M, image)
                Recursive_division(r1, r1, cm+1, c2, M, image)
        
        
        num_rows = self.num_rows
        num_cols = self.num_cols
        r1 = 0
        r2 = num_rows-1
        c1 = 0
        c2 = num_cols-1
        
        M = np.zeros((num_rows,num_cols,5), dtype=np.uint8)

        image = np.zeros((num_rows*10,num_cols*10), dtype=np.uint8)
        
        Recursive_division(r1, r2, c1, c2, M, image)
        Map = draw_maze(num_rows, num_cols, M, image)
        return Map